﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.IO;
using System.Windows.Media.Animation;


namespace WGM_Client_Net35
{
    /// <summary>
    /// Interaction logic for OnlineOptionsWindow.xaml
    /// </summary>
    public partial class OnlineOptionsWindow : Window
    {
        private WGM_Service.UserOptions _myCurrentOptions;
        private WGM_Service.UserOptions _tempOptions;
        private MainWindow _parent;
        private bool _imageChanged = false;
        private ConnectionHandlerObject _cho;
        private System.Drawing.Image _currentImage;
        private System.Drawing.Image _tempImage;
        private ImageSource _defaultSrc;
        public OnlineOptionsWindow(WGM_Service.UserOptions myOptions, ConnectionHandlerObject cho, MainWindow parent)
        {
            _myCurrentOptions = myOptions;
            _parent = parent;
            _cho = cho;
            InitializeComponent();
            _defaultSrc = _displayImage.Source;
            LoadCurrentSettings();
            
        }
        private void LoadCurrentSettings()
        {
            try
            {
                
                _imageChanged = false;
                _tempOptions = _myCurrentOptions;
                _displayNameTB.Text = _myCurrentOptions.DisplayName;
                _displayStatusTB.Text = _myCurrentOptions.UserStatus;
                _fontColourR.Value = _myCurrentOptions.FontColourR;
                _fontColourG.Value = _myCurrentOptions.FontColourG;
                _fontColourB.Value = _myCurrentOptions.FontColourB;
                _fontSize.Value = _myCurrentOptions.FontSize;
                _isBold.IsChecked = _myCurrentOptions.IsFontBold;
                _isItalics.IsChecked = _myCurrentOptions.IsFontItalics;
                _isUnderlined.IsChecked = _myCurrentOptions.IsFontUnderlined;
                _fontChooser.SelectedItem = new FontFamily(_myCurrentOptions.UserFontFace);
                SetReflection();
                BackgroundWorker imageWorker = new BackgroundWorker();
                imageWorker.DoWork += new DoWorkEventHandler(imageWorker_DoWork);
                imageWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(imageWorker_RunWorkerCompleted);
                imageWorker.RunWorkerAsync();
            }
            catch (Exception ex)

            { }
        }

        void imageWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {

                if (!_imageChanged)
                {
                    byte[] imageArr = e.Result as byte[];
                    _tempImage = _currentImage = HelperFunctions.ByteArrayToImage(imageArr);
                    
                    
                    _clearImgBtn.Visibility = Visibility.Visible;
                    DoubleAnimation fadeIn = new DoubleAnimation(0,1,new Duration(new TimeSpan(0,0,3)));
                    _displayImage.BeginAnimation(Image.OpacityProperty, fadeIn);
                    _displayImage.Source = HelperFunctions.GetBitmapFromImage(_currentImage);
                    SetReflection();
                }
            }

        }

        void imageWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = _cho.RetrieveUserImage(_cho.CurrentUserName);
        }
        private void ColChooser_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                _fontChooser.Foreground = new SolidColorBrush(Color.FromRgb((byte)_fontColourR.Value,
                                                                             (byte)_fontColourG.Value,
                                                                             (byte)_fontColourB.Value));
            }
            catch { }

            
        }
        private void _doneBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _tempOptions.FontColour = System.Drawing.Color.FromArgb((byte)_fontColourR.Value,
                                                                      (byte)_fontColourG.Value,
                                                                      (byte)_fontColourB.Value).ToArgb();
            _tempOptions.FontColourR = (int)_fontColourR.Value;
            _tempOptions.FontColourG = (int)_fontColourG.Value;
            _tempOptions.FontColourB = (int)_fontColourB.Value;
            _tempOptions.DisplayName = _displayNameTB.Text;
            _tempOptions.UserStatus = _displayStatusTB.Text;
            _tempOptions.UserFontFace = (_fontChooser.Text);
            _tempOptions.FontSize = (int)_fontSize.Value;
            _tempOptions.IsFontBold = _isBold.IsChecked == true;
            _tempOptions.IsFontItalics = _isItalics.IsChecked == true;
            _tempOptions.IsFontUnderlined = _isUnderlined.IsChecked == true;
            
            SendOptions();
            
        }
        private void SendOptions()
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            AllControls.IsEnabled = false;
            bgw.RunWorkerAsync();
        }
        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            AllControls.IsEnabled = false;
            if ((bool)e.Result == true)
            {
                _cho.SetMyUserOptions(_tempOptions);
                _parent.SetAllTabsData(_tempOptions);
                _parent.SetCurrentDisplayInfo(_tempOptions.DisplayName, _tempOptions.UserStatus);
                _parent.SetCurrentImage(_currentImage);
                this.Close();
            }
            else
            {
                MessageBox.Show("Error setting options, try again later.", "WGM Minor error", MessageBoxButton.YesNo, MessageBoxImage.Question);
            }
        }

        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = _cho.SetUserOptions(_cho.CurrentUserName, _tempOptions);
                if (_imageChanged)
                {
                    if(_currentImage == null)
                        e.Result = _cho.SetUserImage(_cho.CurrentUserName, null);
                    else
                        e.Result = _cho.SetUserImage(_cho.CurrentUserName, HelperFunctions.ImageToByteArray(_currentImage, System.Drawing.Imaging.ImageFormat.Bmp));
                }
            }
            catch { }
        }

        private void _resetBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            LoadCurrentSettings();
            
        }

        private void _fontSize_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            _fontChooser.FontSize = e.NewValue;
        }

        private void CheckChanged(object sender, RoutedEventArgs e)
        {
            if (_isBold.IsChecked == true)
                _fontChooser.FontWeight = FontWeights.Bold;
            else
                _fontChooser.FontWeight = FontWeights.Regular;
            if (_isItalics.IsChecked == true)
                _fontChooser.FontStyle = FontStyles.Italic;   
            else
                _fontChooser.FontStyle = FontStyles.Normal ; 
                
        }

        private void CancelBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void _displayImage_MouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter = "*.bmp|*.bmp|*.png|*.png|*.jpg|*.jpg|*.jpeg|*.jpeg";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FileInfo fi = new FileInfo(ofd.FileName);
                if (fi.Length > (1024 * 500))
                {
                    MessageBox.Show("Please select a file smaller than 500Kb.", "Wayne's Global Messenger",MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                try
                {
                    System.Drawing.Image myImage = System.Drawing.Image.FromFile(ofd.FileName);
                    _currentImage = myImage;
                    _imageChanged = true;
                    _displayImage.Source = HelperFunctions.GetBitmapFromImage(_currentImage);
                    VisualBrush reflect = new VisualBrush(_displayImage);
                    SetReflection();
                    _clearImgBtn.Visibility = Visibility.Visible;

                    

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Please select a valid image file.\r\n" + ex.ToString(), "Wayne's Global Messenger", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
        }
        private void SetReflection()
        {
            VisualBrush reflect = new VisualBrush(_displayImage);
            _reflection.Width = _displayImage.Width;
            _reflection.Height = _displayImage.Height;
            reflect.Transform = new ScaleTransform(1, -1, _reflection.Width, _reflection.Height / 2);

            _reflection.Background = reflect;

        }

        private void _clearImgBtn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _currentImage = null;
            _imageChanged = true;
            _clearImgBtn.Visibility = Visibility.Hidden;
            _displayImage.Source = _defaultSrc;
            SetReflection();
        }
    }
}
